package com.kaigejava.juc.volatitle;

/**
 * @author kaigejava
 * volatile的atomic  不能保证原子性演示代码
 */
public class VolatileAtomicDemo12 {
    public static void main(String[] args) {
        MyVolatileNumber myVolatileNumber = new  MyVolatileNumber();
        for(int i = 0;i<50;i++){
            new Thread(()->{
                for(int x = 0;x<1000000;x++){
                    myVolatileNumber.numberAdd();
                }
            },"线程"+(i+1)).start();
        }
      //这里也可以使用thread.sleep
        while (Thread.activeCount()>2){ //如果当前运行线程总数量大于2.主线程就yield
            Thread.yield();
        }
        System.out.println("====="+Thread.currentThread().getName()+"===最终number的值为:"+myVolatileNumber.number);

    }
}



/**
 * 内部类
 */
class MyVolatileNumber {
    //修改number为volatile
    volatile int number = 0;
   public void numberAdd(){
        number++;
   }
}
